from django.db import transaction
from rest_framework import serializers
import logging

from rest_framework.response import Response

from users.models import User, UserImage

logger = logging.getLogger('django')

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id','username','email','nickname','user_pic','password')
        extra_kwargs = {
            'password':{
                'min_length':8,
                'max_length':20,
                'write_only':True
            },
            'username': {
                'min_length': 3,
                'max_length': 20,
                'required': True,
            },
            'email':{'required':False},
            'nickname': {'required': False},
            'user_pic': {'required': False},

        }

    def create(self, validated_data):
        # try:
            user = super().create(validated_data)
            user.is_staff = True
            user.set_password(validated_data['password'])
            user.save()
        # except Exception as e:
        #     logger.error(e)
        #     user = User.objects.get(username = 'error_user_info')
        # user = User.objects.create_user()
            return user
    # def update(self, instance, validated_data):
    #     pass

class UserImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserImage
        fields = '__all__'

    def create(self, validated_data):
        with transaction.atomic():
                # 开启事务
            save_id = transaction.savepoint()
            try:
                instance = UserImage.objects.create(**validated_data)
                instance.user.user_pic=instance.cover_img.name
                instance.user.save()
            except Exception as e:
                transaction.savepoint_rollback(save_id)
                print(e)
                return serializers.ValidationError('数据库错误')
            else:
                transaction.savepoint_commit(save_id)
                return instance